package com.ruoyi.system.service.impl;

import java.util.*;
import java.util.stream.Collectors;

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.domain.SysTreeDictData;
import com.ruoyi.system.mapper.SysTreeDictDataMapper;
import org.apache.commons.lang3.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.PlanMapper;
import com.ruoyi.system.domain.Plan;
import com.ruoyi.system.service.IPlanService;

/**
 * 计划Service业务层处理
 * 
 * @author genghz
 * @date 2021-12-19
 */
@Service
public class PlanServiceImpl implements IPlanService 
{
    @Autowired
    private PlanMapper planMapper;

    /**
     * 查询计划
     * 
     * @param planId 计划主键
     * @return 计划
     */
    @Override
    public Plan selectPlanByPlanId(Long planId)
    {
        return planMapper.selectPlanByPlanId(planId);
    }

    /**
     * 查询计划列表
     * 
     * @param plan 计划
     * @return 计划
     */
    @Override
    public List<Plan> selectPlanList(Plan plan)
    {
        return planMapper.selectPlanList(plan);
    }

    /**
     * 新增计划
     * 
     * @param plan 计划
     * @return 结果
     */
    @Override
    public int insertPlan(Plan plan)
    {
        String username = SecurityUtils.getUsername();
        String deptName = SecurityUtils.getLoginUser().getUser().getDept().getDeptName();
        String planCode = "P_" + DateUtils.parseDateToStr("yyyyMMdd", new Date())+ "_" + RandomUtils.nextInt();

        plan.setPlanCode(planCode);
        plan.setCreateDate(new Date());
        plan.setStatus(0);
        plan.setVersion(1);
        plan.setUserName(username);
        plan.setDeptName(deptName);
        return planMapper.insertPlan(plan);
    }

    /**
     * 修改计划
     * 
     * @param plan 计划
     * @return 结果
     */
    @Override
    public int updatePlan(Plan plan)
    {
        return planMapper.updatePlan(plan);
    }

    /**
     * 批量删除计划
     * 
     * @param planIds 需要删除的计划主键
     * @return 结果
     */
    @Override
    public int deletePlanByPlanIds(Long[] planIds)
    {
        return planMapper.deletePlanByPlanIds(planIds);
    }

    /**
     * 删除计划信息
     * 
     * @param planId 计划主键
     * @return 结果
     */
    @Override
    public int deletePlanByPlanId(Long planId)
    {
        return planMapper.deletePlanByPlanId(planId);
    }

    @Autowired
    private SysTreeDictDataMapper sysTreeDictDataMapper;

    @Override
    public List<Map> staticsDept(Long planId) {
        List<Map> maps = planMapper.staticsDept(planId);
        for (Map map : maps) {
            SysTreeDictData sysTreeDictData = sysTreeDictDataMapper.selectSysTreeDictDataByDataId((Long) map.get("sys_lel1"));
            map.put("name", sysTreeDictData.getDictLabel());
        }
        return maps;
    }

    @Override
    public Object[] staticsDept1(Long planId) {
        List<Map> maps = planMapper.staticsDept1(planId);
        for (Map map : maps) {
            if(!Objects.isNull(map) && !Objects.isNull(map.get("sys_lel2"))) {
                SysTreeDictData sysTreeDictData = sysTreeDictDataMapper.selectSysTreeDictDataByDataId((Long) map.get("sys_lel2"));
                map.put("name", sysTreeDictData.getDictLabel());
            }
        }
        Object[] names = maps.stream().map(x -> Objects.isNull(x)?"":x.getOrDefault("name", "")).collect(Collectors.toList()).toArray();
        return names ;
    }

    @Override
    public List<Object> staticsDept2(Long planId) {
        List<Object> list = new ArrayList<>();

        String start = "2021-10-01" ;
        String end = "2025-12-31" ;
        Date startDate = DateUtils.parseDate(start);
        int monthDiff = getMonthDiff(startDate, DateUtils.parseDate(end));
        String[] array = new String[monthDiff];
        for(int i = 0; i < monthDiff; i++) {
            array[i] = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD,DateUtils.addMonths(startDate, i));
        }

        List<Map> maps = planMapper.staticsDept1(planId);
        for (Map map : maps) {
            List<Map> cube1 = new ArrayList<>();
            List<Map> cube = planMapper.staticsDept2(planId, Objects.isNull(map)?null:(Long) map.get("sys_lel2"));
            for (String s : array) {
                Optional<Map> date = cube.stream().filter(x ->
                               DateUtils.parseDateToStr(DateUtils.YYYY_MM, (Date) x.get("date")).
                        equals(DateUtils.parseDateToStr(DateUtils.YYYY_MM,DateUtils.parseDate(s)))).findFirst();
                if(date.isPresent()) {
                    Map map1 = date.get();
                    map1.put("text", map1.get("text") +"(" +DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, (Date) map1.get("date")) + ")");
                    cube1.add(map1);
                } else {
                    HashMap<Object, Object> objectObjectHashMap = new HashMap<>();
                    objectObjectHashMap.put("date", s);
                    cube1.add(objectObjectHashMap);
                }
            }
            list.add(cube1);

        }

        return list ;
    }

    /**
     * 获取两个日期相差的月数
     */
    public static int getMonthDiff(Date d1, Date d2) {
        Calendar c1 = Calendar.getInstance();
        Calendar c2 = Calendar.getInstance();
        c1.setTime(d1);
        c2.setTime(d2);
        int year1 = c1.get(Calendar.YEAR);
        int year2 = c2.get(Calendar.YEAR);
        int month1 = c1.get(Calendar.MONTH);
        int month2 = c2.get(Calendar.MONTH);
        int day1 = c1.get(Calendar.DAY_OF_MONTH);
        int day2 = c2.get(Calendar.DAY_OF_MONTH);
        // 获取年的差值
        int yearInterval = year1 - year2;
        // 如果 d1的 月-日 小于 d2的 月-日 那么 yearInterval-- 这样就得到了相差的年数
        if (month1 < month2 || month1 == month2 && day1 < day2) {
            yearInterval--;
        }
        // 获取月数差值
        int monthInterval = (month1 + 12) - month2;
        if (day1 < day2) {
            monthInterval--;
        }
        monthInterval %= 12;
        int monthsDiff = Math.abs(yearInterval * 12 + monthInterval);
        return monthsDiff;
    }

}
